<?php

/**
 * 附件模型
 * File Name：AttachmentModel.php
 * File Encoding：UTF-8
 * File New Time：2014-8-21 14:38:32
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class AttachmentModel extends BaseModel {

    public function tableName() {
        return '{{attachment}}';
    }

    public function rules() {
        return array(
            array('filename,filepath,filesize,fileext,isimage,isthumb,userid,isadmin,uploadtime,uploadip', 'safe'),
        );
    }

    //数据保存前回调处理
    protected function beforeSave() {
        if ($this->isNewRecord) {
            //改变数据
            $this->uploadtime = time();
            $this->uploadip = GuestDataModel::model()->getForwardedForIp();
        }
        return true;
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 取得上传保存目录
     * @param type $dateFormat 目录格式
     * @return string
     */
    public function getFilePath($dateFormat = 'Y/m') {
        $filePath = 'file/' . date($dateFormat ? $dateFormat : 'Y/m') . '/';
        return $filePath;
    }

    /**
     * 根据附件aid删除附件
     * @param type $aid 
     * @return boolean
     */
    public function deleteFileByAid($aid) {
        if (empty($aid)) {
            return false;
        }
        if (is_array($aid)) {
            $data = $this->findAll($this->where(array('aid' => array('IN', $aid))));
        } else {
            $data = $this->findAll($this->where(array('aid' => $aid)));
        }
        if (empty($data)) {
            return false;
        }
        require_once Yii::app()->basePath . '/extensions/Oss/sdk.class.php';
        $oss_sdk_service = new ALIOSS();
        $oss_sdk_service->set_debug_mode(true);
        foreach ($data as $rs) {
            $oss_sdk_service->delete_object(UploadFile::getInstance()->bucket, $rs->filepath);
            $rs->delete();
        }
        return true;
    }

    /**
     * 记录上传
     * @param type $file
     * @param type $isOss
     * @return boolean
     */
    public function record($file, $isOss = true) {
        if (empty($file) || !is_array($file)) {
            return false;
        }
        unset($this->aid);
        $this->filename = $file['name'];
        $this->filepath = $file['savepath'] . $file['savename'];
        $this->filesize = $file['size'];
        $this->fileext = $file['extension'];
        if (GROUP_NAME == 'admin') {
            $this->isadmin = 1;
            $this->userid = AdminBase::$uid;
        } else {
            $this->isadmin = 0;
            $this->userid = Yii::app()->user->id;
        }
        $this->isimage = in_array($file['extension'], array('jpg', 'jpeg', 'png', 'gif')) ? 1 : 0;
        $this->isthumb = 0;
        $this->setIsNewRecord(true);
        if ($this->validate() && $this->save()) {
            return $this->primaryKey;
        }
        return false;
    }

    /**
     * 设置upload上传的json格式cookie 
     * @param type $aid 附件ID
     * @param type $src 附件地址
     * @param type $filename 附件名称
     * @return boolean 返回布尔值
     */
    public function upload_json($aid, $src, $filename) {
        $arr['aid'] = $aid;
        $arr['src'] = trim($src);
        $arr['filename'] = urlencode($filename);
        $json_str = json_encode($arr);
        $cookie = Yii::app()->request->getCookies();
        $att_arr_exist = $cookie['att_json'];
        $att_arr_exist_tmp = explode('||', $att_arr_exist);
        if (is_array($att_arr_exist_tmp) && in_array($json_str, $att_arr_exist_tmp)) {
            return true;
        } else {
            $json_str = $att_arr_exist ? $att_arr_exist . '||' . $json_str : $json_str;
            $cookie = new CHttpCookie('att_json', $json_str);
            Yii::app()->request->cookies['att_json'] = $cookie;
            return true;
        }
    }

    /**
     * 取得文件扩展
     * @param type $filename 文件名
     * @return type 后缀
     */
    public function fileext($filename) {
        $pathinfo = pathinfo($filename);
        return $pathinfo['extension'];
    }

    /**
     * 返回附件类型图标
     * @param $file 附件名称
     * @param $type png为大图标，gif为小图标
     */
    public function file_icon($file, $type = 'png') {
        $ext_arr = array('doc', 'docx', 'ppt', 'xls', 'txt', 'pdf', 'mdb', 'jpg', 'gif', 'png', 'bmp', 'jpeg', 'rar', 'zip', 'swf', 'flv');
        $ext = fileext($file);
        if ($type == 'png') {
            if ($ext == 'zip' || $ext == 'rar')
                $ext = 'rar';
            elseif ($ext == 'doc' || $ext == 'docx')
                $ext = 'doc';
            elseif ($ext == 'xls' || $ext == 'xlsx')
                $ext = 'xls';
            elseif ($ext == 'ppt' || $ext == 'pptx')
                $ext = 'ppt';
            elseif ($ext == 'flv' || $ext == 'swf' || $ext == 'rm' || $ext == 'rmvb')
                $ext = 'flv';
            else
                $ext = 'do';
        }
        $config = cache('Config');
        if (in_array($ext, $ext_arr)) {
            return $config['siteurl'] . 'statics/images/ext/' . $ext . '.' . $type;
        } else {
            return $config['siteurl'] . 'statics/images/ext/blank.' . $type;
        }
    }

    /**
     * 根据文件扩展名来判断是否为图片类型
     * @param type $file 文件名
     * @return type 是图片类型返回 true，否则返回 false
     */
    public function isImage($file) {
        $ext_arr = array('jpg', 'gif', 'png', 'bmp', 'jpeg', 'tiff');
        //取得扩展名
        $ext = $this->fileext($file);
        return in_array($ext, $ext_arr) ? true : false;
    }

}
